package com.wqs.tool.datainit.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import com.google.gson.Gson;
import com.wqs.tool.datainit.common.Constant;
import com.wqs.tool.datainit.entity.Task;
import com.wqs.tool.datainit.exception.NotFindNodeException;

import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Dom4jUtils {

	
	public static Task getTask(File file) {
		Task task = null;
		
		SAXReader reader = new SAXReader();
		Document document = null;
		try {
			document = reader.read(file);
			Element root = document.getRootElement();
			//判断是否有task节点
			Node taskNode = root.selectSingleNode(Constant.XPATH_SEPARATOR+Constant.NODE_TASK);
			if(taskNode==null) {
				throw new NotFindNodeException(Constant.NODE_TASK);
			}else {
				task = new Task();
				Node typeNode = taskNode.selectSingleNode(Constant.NODE_TYPE);
				if(typeNode == null ) {
					throw new NotFindNodeException(Constant.NODE_TYPE);
				}else {
					 String type = typeNode.getText();
					 task.setType(type);
					 
					 //根据类型解析
					 switch(type) {
					 	case "1" :
					 		
					 		try {
					 			AnalysisUtils.analysisTypeOne(task,taskNode);
					 		}catch(NotFindNodeException ne) {
					 			log.error(ne.getMessage());
					 		}
					 		break;
					 	
					 	case "2" :
					 		
					 		try {
					 			AnalysisUtils.analysisTypeTwo(task,taskNode);
					 		}catch(NotFindNodeException ne) {
					 			log.error(ne.getMessage());
					 		}
					 		
					 		break;
					 	
					 	case "3" :
					 		
					 		try {
					 			AnalysisUtils.analysisTypeThree(task,taskNode);
					 		}catch(NotFindNodeException ne) {
					 			log.error(ne.getMessage());
					 		}
					 		
					 		break;
					 
					 }
				}
			}
			
			
			
			
		} catch (Exception e) {
			 e.printStackTrace();
		}
		
		return task;
	}
	
	
	public static void main(String[] args) throws IOException  {
		File file = FileUtils.getFileFromClasspath("tasks/test.xml");
		Task task = getTask(file);
		Gson gson = new Gson();
		System.out.println(gson.toJson(task));
	}
}
